package com.joplus.housekeeper.services;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.SmsMessage;
import android.util.Log;

import com.joplus.housekeeper.utils.L;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 短信监听
 * Created by tangdehao on 16/5/12.
 */
public class SMSReceiver extends BroadcastReceiver {

    public static final String TAG = "SMSReceiver";
    public static final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED";

    @Override
    public void onReceive(Context context, Intent intent) {

        if (intent.getAction().equals(SMS_RECEIVED_ACTION)) {
            SmsMessage[] messages = getMessagesFromIntent(intent);
            for (SmsMessage message : messages) {
                Log.e(TAG, message.getOriginatingAddress() + " : " +
                        message.getDisplayOriginatingAddress() + " : " +
                        message.getDisplayMessageBody() + " : " +
                        message.getTimestampMillis());
                String smsContent = message.getDisplayMessageBody();

                Log.e(TAG, smsContent);

                String verifyCode = getCode(smsContent,4);

                Intent verifyIntent = new Intent();
                verifyIntent.setAction("verify_code_action");
                verifyIntent.putExtra("verifyCode",verifyCode);
                context.sendBroadcast(verifyIntent);
                L.e("短信验证码为: "+verifyCode);
            }
        }
    }

    /**
     * 从短信字符窜提取验证码
     * @param body 短信内容
     * @param verifyCodeLength  验证码的长度 一般6位或者4位
     * @return 接取出来的验证码
     */
    private  String getCode(String body, int verifyCodeLength) {
        // 首先([a-zA-Z0-9]{YZMLENGTH})是得到一个连续的六位数字字母组合
        // (?<![a-zA-Z0-9])负向断言([0-9]{YZMLENGTH})前面不能有数字
        // (?![a-zA-Z0-9])断言([0-9]{YZMLENGTH})后面不能有数字出现
        Pattern p = Pattern
                .compile("(?<![a-zA-Z0-9])([a-zA-Z0-9]{" + verifyCodeLength + "})(?![a-zA-Z0-9])");
        Matcher m = p.matcher(body);
        if (m.find()) {
            return m.group(0);
        }
        return "";
    }

    public final SmsMessage[] getMessagesFromIntent(Intent intent) {
        Object[] messages = (Object[]) intent.getSerializableExtra("pdus");
        byte[][] pduObjs = new byte[messages.length][];
        for (int i = 0; i < messages.length; i++) {
            pduObjs[i] = (byte[]) messages[i];
        }
        byte[][] pdus = new byte[pduObjs.length][];
        int pduCount = pdus.length;
        SmsMessage[] msgs = new SmsMessage[pduCount];
        for (int i = 0; i < pduCount; i++) {
            pdus[i] = pduObjs[i];
            msgs[i] = SmsMessage.createFromPdu(pdus[i]);
        }
        return msgs;
    }
}
